<?php

class VoteModel extends Model {

	public function addVote($post, $mid = 0) {
		$mid   = ($mid == 0) ? $_SESSION['mid'] : $mid;
		$uname = getUserName($mid);

		$post['title'] = t($post['title']);
		if($post['deadline_type'] == 'u') {
			$deadline = mktime(0,0,0,$post["month"],$post["day"],$post["year"]);
		}else {
			$deadline = mktime(0,0,0,date('m'),date('d') + intval($post['deadline_type']),date('Y'));
		}

		if($deadline < time()) {
			return -1; // 投票的截止时间不能早于发起投票的时间！
		}

		//检测选项是否重复
		$opt_test = array_filter($post['opt']);
		$opt_test_count = count(array_unique( $opt_test ));
		if( $opt_test_count < count($opt_test) ) {
			return -2; //投票不允许有重复项
		}

		//投票表
		$voteDao  = M('vote');
		$voteUser = M('vote_user');

		$data['uid']		= $mid;
		$data['name']		= $uname;
		$data['title']		= $post['title'];
		$data['explain']	= $post['explain'];
		$data['type']		= $post['type'];
		$data['deadline']	= $deadline;
		$data['cTime']		= time();
		$data['app']		= $post['app'];
		$data['field']		= $post['field'];
		$data['fieldId']	= $post['fieldId'];
		$data['is_anonymous']	= $post['is_anonymous'];
		$vote_id = $voteDao->add($data);
		unset($data);

		$data['vote_id']	= $vote_id;
		$data['uid']		= $mid;
		$data['name']		= $uname;
		$data['cTime']		= time();
		$voteUser->add($data);
		unset($data);

		//选项表
		$optDao = M('vote_opt');
		foreach($post["opt"] as $v) {
			if(!$v) continue;
			$data["vote_id"] = $vote_id;
			$data["name"]    = t($v);
			$optDao->add($data);
		}

		return $vote_id;
	}
}

?>